package com.plan.base.aop;

import com.plan.base.entity.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * 结果拦截器
 * 目前需求是：统一处理语言
 *
 * @author zcl
 */
@Aspect
@Component
public class ResultHandlerAspect {


    @Around("execution(* *..*.*(..)) && within(@org.springframework.web.bind.annotation.RestController *)")
    public Object handleResult(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前请求的HttpServletRequest
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 获取请求的语种
        Locale locale = request.getLocale();

        // 执行原方法
        Object result = joinPoint.proceed();

        // 动态检查返回值是否为Result类型
        if (result instanceof Result) {
            Result<?> res = (Result<?>) result;
            res
                    .setMsg(Result.getMessages(res.getCode(), locale, res.getArgs()))
                    // 返回结果里不需要这个参数了，所以置空
                    .setArgs(null);
            return res;
        }

        // 如果不是Result类型，直接返回原结果
        return result;
    }

}